<template>
  <div v-loading="loading">
    <common-page
      ref="common"
      :ccode="ccode"
      @hook:created="commonCreated"
    >
      <template #_rating="{form, conf, complexInstance, fullData}">
        <div>
          <p v-if="hasRatingForm" class="label">{{ ratingFormName }}</p>
          <complex-form2
            v-if="hasRatingForm"
            ref="ratingForm"
            :layout="ratingLayout"
            :res-data="ratingForm"
            :fields="ratingForm.tableInfo.fieldList"
            :data="ratingForm.data"
            :disabled="!!readonly"
            :field-rule="ratingForm.rule"
            :complex-config="ratingFormConfig"
            :p-instance="this"
          />
          <p v-if="hasRatingList" class="label">评分记录</p>
          <approve-history v-if="hasRatingList" :approval-list="ratingList" />
        </div>
      </template>
      <div class="form-info">
        <sticky :sticky-top="stickyTop" :z-index="100" class-name="btn-sticky" style="margin-bottom:10px">
          <div class="tool-container">
            <el-button size="small" type="primary" icon="el-icon-download" @click="screenshot">下载表单</el-button>
            <el-button
              @click="backList"
            >
              返回
            </el-button>
          </div>
        </sticky>
        <div id="picture">
          <p class="label">审批表单</p>
          <complex-form2
            v-if="layout"
            ref="todoForm"
            :layout="layout"
            :res-data="customForm"
            :fields="customForm.tableInfo.fieldList"
            :data="customForm.data"
            :field-rule="customForm.rule"
            :complex-config="formConfig"
            disabled
            is-flow
          />
          <p class="label" style="margin-top:12px;">审批历史</p>
          <lb-table
            v-if="tableVisible"
            :column="tableColumn"
            :data="tableData"
            :table-info="tableInfo"
            background
          />
        </div>
      </div>
    </common-page>
  </div>
</template>

<script>
import {
  invokeMethod
} from '@/api/common'
import {
  runTask,
  saveWf
} from '@/api/workflow'
import html2canvas from 'html2canvas'
import {

} from '@/utils/index'
import Sticky from '@/components/Sticky/index.vue'
import { mapGetters } from 'vuex'
import Qibao from '@/admin'
const { tableFunc } = Qibao
import ApproveHistory from '@/components/WorkFlow/approveHistory.vue'
export default {
  name: 'WorkflowMonitor',
  components: {
    Sticky,
    ApproveHistory
  },
  data() {
    return {
      activeName: 'form',
      cmdList: [],
      customForm: {},
      layout: null,
      cmdMemo: '',
      loading: true,
      btnLoading: false,
      tableVisible: false,
      tableColumn: [],
      tableData: [],
      tableInfo: {},
      todoInfo: {},
      formConfig: {},
      ratingForm: {}, // 评分表单
      ratingFormConfig: {}, // 评分表单配置项
      ratingLayout: null, // 评分表单布局
      ratingList: null // 评分记录
    }
  },
  computed: {
    ...mapGetters([
      'isShowNav'
    ]),
    ccode: function() {
      return this.$route.meta.code
    },
    fInsId: function() {
      return this.$route.query.parentDataId
    },
    oInsId: function() {
      return this.$route.query.originalDataId
    },
    readonly: function() {
      return true
    },
    allowSave: function() {
      return this.todoInfo.allowSave
    },
    allowSubmit: function() {
      return this.todoInfo.allowSubmit
    },
    stickyTop: function() {
      return this.isShowNav ? 90 : 0
    },
    hasRatingForm: function() {
      return !!this.ratingLayout
    },
    ratingFormName: function() {
      return this.ratingForm.name
    },
    hasRatingList: function() {
      return !!this.ratingList
    }
  },
  mounted: function() {
    this.getTodoInfo()
  },
  methods: {
    reloadForm() {
      this.getTodoInfo()
    },
    commonCreated() {

    },
    // 获取代办事项
    getTodoInfo() {
      this.layout = null
      this.ratingLayout = null
      this.approvalList = {}
      const params = {
        methodId: '916518482282024960',
        data: {
          fInsId: this.fInsId,
          oInsId: this.oInsId
        }
      }
      invokeMethod(params).then(res => {
        this.todoInfo = res.data
        this.cmdList = (res.data.cmdList || []).sort((pre, next) => {
          return pre.order_id > next.order_id ? 1 : -1
        })
        this.customForm = res.data.customForm || {}
        this.formConfig = this.customForm.form_config ? JSON.parse(this.customForm.form_config) : {}
        this.layout = JSON.parse(this.customForm.layout)
        const {
          tableInfo,
          data
        } = res.data.approvalList
        this.tableInfo = tableInfo
        this.tableColumn = tableFunc.createTableColumn(tableInfo)
        this.tableData = tableFunc.createTableData(data)
        this.tableVisible = true
        this.cmdMemo = this.todoInfo.processMemo || ''
        // 评分表单
        this.ratingForm = res.data.ratingForm || {}
        this.ratingFormConfig = this.ratingForm.form_config ? JSON.parse(this.ratingForm.form_config) : {}
        if (this.ratingForm?.layout) {
          this.ratingLayout = JSON.parse(this.ratingForm.layout)
        }
        this.ratingList = res.data.ratingList
      }).finally(() => {
        this.loading = false
      })
    },
    // 返回列表页
    backList() {
      const view = this.$route
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        this.$router.back()
      })
    },
    // 下载
    screenshot() {
      const targetDom = document.getElementById('picture')
      const copyDom = targetDom.cloneNode(true)
      // 富文本特殊处理
      let width = targetDom.scrollWidth
      const height = targetDom.scrollHeight
      let increaseHeight = 0
      const tinymces = targetDom.querySelectorAll('.tinymce-container') || []
      tinymces.forEach(item => {
        increaseHeight += item.scrollHeight - item.clientHeight
      })
      const copyTinymces = copyDom.querySelectorAll('.tinymce-container') || []
      copyTinymces.forEach(item => {
        item.style.maxHeight = 'none'
      })
      // 表格特殊处理
      const tables = targetDom.querySelectorAll('.el-table') || []
      tables.forEach(item => {
        const bodyDom = item.querySelector('.el-table__body-wrapper')
        if (bodyDom) {
          width = Math.max(width, bodyDom.scrollWidth)
          console.log(bodyDom.scrollHeight - bodyDom.clientHeight)
          increaseHeight += bodyDom.scrollHeight - bodyDom.clientHeight
        }
      })
      const copyTables = copyDom.querySelectorAll('.el-table') || []
      copyTables.forEach(item => {
        item.style.maxHeight = 'none'
        item.style.height = 'unset'
        if (item.querySelector('.el-table__body-wrapper')) {
          item.querySelector('.el-table__body-wrapper').style.maxHeight = 'none'
          item.querySelector('.el-table__body-wrapper').style.height = 'unset'
        }
      })
      console.log(increaseHeight)

      const scrollWidth = width + 100
      const scrollHeight = height + increaseHeight + 40
      copyDom.style.width = scrollWidth + 'px'
      copyDom.style.height = scrollHeight + 'px'
      copyDom.style.padding = '20px 50px'
      document.body.appendChild(copyDom)
      html2canvas(copyDom, {
        allowTaint: false,
        useCORS: true,
        height: scrollHeight,
        width: scrollWidth
      }).then(canvas => {
        const dataURL = canvas.toDataURL('image/png')
        copyDom.remove()
        const dataImg = new Image()
        dataImg.src = canvas.toDataURL('image/png')
        const alink = document.createElement('a')
        alink.href = dataURL
        alink.download = '审批表单.jpg'
        alink.click()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
p.label{
  font-size: 14px;
  font-weight: bold;
  margin: 8px 0;
}
.tool-container{
  text-align: right;
  margin-top: 10px;
}
.approve-list{
  margin-top: 10px;
}
::v-deep .btn-sticky{
  background: #fff;
  box-sizing: content-box;
  transform: translateY(-6px);
  padding: 6px 0;
  height: fit-content !important;
}
</style>
